<?php

namespace Action;

class Authenticate extends \Library\Action\PortalAction {

	private $_messages = array();
	private $_tabPane;

	public function execute() {
		parent::execute();
		$this->setTitle( 'Authenticate' );
		
		if( !$this->hasParam( 'Action_Authenticate' ) ) {
			return;
		}
		
		unset( $_POST['auth'][0]['password'] );

		$this->_handle( $this->getParams() );
		
		if( $this->hasFailed() ) {
			return;
		}
		
		$this->redirect( './' );
	}
	
	public function hasRemembrance() {
		return isset($_POST['remembrance']) ? $_POST['remembrance'] : false;
	}
	
	public function hasFailed() {
		return count($this->_messages) > 0;
	}
	
	public function getMessages() {
		return $this->_messages;
	}
	
	public function getTabPane() {
		if( $this->_tabPane === null ) {
			$this->_tabPane = new \Library\Widget\TabPane();
			$this->_tabPane
				->getTab( 'basic' )
					->setTitle( 'By password' )
					->setContent( _view( 'Auth', \Library\Auth::get( 'Basic' ) ) )
					->getTabPane()
				->getTab( 'openid' )
					->setTitle( 'By OpenID' )
					->setContent( _view( 'Auth', \Library\Auth::get( 'OpenID' ) ) )
					->getTabPane();
		}
		return $this->_tabPane;
	}
	
	private function _handle( $post ) {

		$post['auth'] = array_filter( $post['auth'], array( $this, '_isFilledIn' ) );
		
		if( !$post['auth'] ) {
			$this->_messages[] = 'You must choose an authentication method';
			return false;
		}
		
		$auth = current($post['auth']);
		$auth = \Library\Auth::get( $auth['kind'] );

		/**
		* Step 2 : Check user existence
		*/
		try {
			$user = $auth->authenticate( current($post['auth']) );
		}
		catch( \Exception $e ) {
			$this->_messages[] = 'Invalid credentials';
			return false;
		}

		/**
		* Step 4 : Store in session
		*/
		$session = \Library\Auth\Session::getSession();
		$session->setUser( $user );

		/**
		* Step 5 : Cookie session
		*/
		if( !$post['remembrance'] ) {
			$session->deleteRemembranceCookie();
		}
		else {
			$session->createRemembranceCookie( $post['password'] );
		}
	}
	
	private function _isFilledIn( $data ) {
	
		_a( preg_match( '/^[A-Za-z]+$/', $data['kind'] ), 'Invalid authentication method' );
		unset( $data['kind'] );
		foreach( $data as $k => $v ) {
			if( !$v ) {
				unset( $data[$k] );
			}
		}
		return $data ? true : false;
	}
}
